package com.icesoft.core.web.helper.http;

import com.icesoft.core.common.util.MD5Util;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class SignUtil {

    private final static String key = "5b8af47892d636624dde271aa5e19938";
    public static final String NONCE_STR_NAME = "nonceStr";
    public static final String TIME_UNIT_NAME = "timeUnit";

    public static String sign(Map<String, String> map, String timeUnit, String nonceStr) {
        Map<String, String> signParam = new HashMap<>(map);
        signParam.put(TIME_UNIT_NAME, timeUnit);
        signParam.put(NONCE_STR_NAME, nonceStr);
        return sign(signParam);
    }

    public static String sign(Map<String, String> map) {
        String stringSignTemp = appendToStr(map);
        log.trace("签名字符串：{}", stringSignTemp);
        return MD5Util.md5(stringSignTemp);
    }

    private static String appendToStr(Map<String, String> map) {
        TreeMap<String, String> paramMap = new TreeMap<>(map);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.append("key=").append(key);
        return sb.toString();
    }
}
